var QueryNonFeedorder = function () {
  var template = /*html*/ `
    <div class="query-non-feedorder" v-loading.fullscreen.lock="loading">
      <div style="margin-top:10px;">
        <search-btn-view btn-text="未生成投料单订单查询" @before-open="resetSearch" @closed="resetDropdown" @search="searchData">
          <div slot="search-content">
            <common-search-form ref="searchRef" :search="search" request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:1}"
              :search-field="searchForm" label-width="auto" input-width="200px">
              <template slot="append">
                <el-form-item label="供方编号">
                  <el-input style="width:200px" v-model="search.providerNo" placeholder="请输入供方编号"></el-input>
                </el-form-item>
                <el-form-item label="订单类型">
                  <sys-autocomplete v-model="search.orderType" :options="orderTypeList" placeholder="请输入订单类型"></sys-autocomplete>
                </el-form-item>
                <el-form-item label="下单日期">
                  <el-date-picker style="width:135px" v-model="search.orderDateStart" value-format="timestamp" :editable="false"
                    :picker-options="startDateOption"></el-date-picker>
                  <span>-</span>
                  <el-date-picker style="width:135px" v-model="search.orderDateEnd" value-format="timestamp" :editable="false"
                    :picker-options="endDateOption"></el-date-picker>
                </el-form-item>
              </template>
            </common-search-form>
            <!--<sys-common-search ref="searchRef" :search="search" request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:1}" 
              :search-field="searchForm" label-width="auto" input-width="200px">
              
            </sys-common-search>-->
          </div>
          <template slot="append">
            <el-button size="medium" type="primary" @click="saveAsFeedAndPurchase">保存为投料单与采购单</el-button>
          </template>
        </search-btn-view>
      </div>
      <div style="margin-bottom:10px;color:#3bb4f2;"> 
        温馨提示:可点击订单查看是否有可用块料
      </div>
      <div v-if="materialTypeCountList.length>0" class="non-feedorder-stat">
        <span v-for="item in materialTypeCountList" :key="'materialType_'+item.materialType">
          {{item.materialType}}:{{item.count}}
        </span>
      </div>
      <div class="non-feedorder-table-div" v-if="dealerList!==null">
        <el-table fit stripe border class="non-feedorder-table small-size-table" ref="nonFeedOrderTable" :data="orderList" style="width:100%;overflow:hidden;" height="parent" 
          :row-class-name="getRowClassName" @row-click="rowClick" @selection-change="selectNonFeedorder">
          <el-table-column :resizable="false" prop="orderDate" label="下单日期" width="90px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="deliveryDate" label="交货日期" min-width="90px" align="center"></el-table-column>
          <el-table-column prop="articleOrderNo" label="客户订单编号" min-width="140px" header-align="center"></el-table-column>
          <el-table-column prop="customer" label="客户" min-width="100px" header-align="center"></el-table-column>
          <el-table-column prop="articleNo" label="客户型号" min-width="130px" header-align="center"></el-table-column>
          <el-table-column prop="companyOrderId" label="订单编号" min-width="140px" header-align="center"></el-table-column>
          <el-table-column prop="company" label="工厂型号" min-width="130px" header-align="center"></el-table-column>
          <el-table-column prop="providerNo" label="供方编号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="materialType" label="物料类型" min-width="130px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" label="供应商" width="190px" header-align="center">
            <template slot-scope="scope">
              <table-dealer-select v-if="scope.row.canSelect" :key="scope.row._dataId" v-model="scope.row.provider" style="width:180px" v-model="scope.row.provider" :order="scope.row"
                :dealer-list="dealerList" :dealer-obj="allDealerObj">
              </table-dealer-select>
              <span v-else>{{scope.row.providerName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="color" label="编号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="colorDescription" label="描述" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="materialModel" label="规格型号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="materialDeptName" label="物料部门" min-width="120px" header-align="center"></el-table-column>
          <el-table-column prop="copefeedTotal" label="投料数(付)" min-width="110px" align="center"></el-table-column>
          <el-table-column auto-width label="投料数" min-width="130px" header-align="center">
            <template slot-scope="scope" v-if="scope.row.canSelect">
              <template v-if="(canUpdateFeedCount||scope.row.unit!=='付')&&scope.row.workshop===null">
                <el-input-number is-decimal-zero class="table-input" v-model="scope.row.feedTotal" :min="0" :precision="SysUtil.getMaterialNumberPrecision(scope.row.unit,4)" size="mini"
                  :controls="false" style="width:120px" @click.native.stop></el-input-number>
                <span>{{scope.row.unit}}</span>
              </template>
              <div v-else>
                <span>{{scope.row.feedTotal}}</span>
                <span>{{scope.row.unit}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column auto-width label="实际投料数" min-width="130px" header-align="center">
            <template slot-scope="scope" v-if="scope.row.canSelect">
              <template v-if="scope.row.unit!=='付'">
                <el-input-number is-decimal-zero v-model="scope.row.actualFeedCount" class="table-input" :min="0.0001" :precision="4" size="mini" :controls="false" @click.native.stop
                  style="width:120px" @change="actualFeedCountChange(scope.row)"></el-input-number>
                <span>{{scope.row.unit}}</span>
              </template>
              <div v-else>
                <span>{{scope.row.actualFeedCount}}</span>
                <span>{{scope.row.unit}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="availableCount" label="可用数" min-width="110px"></el-table-column>
          <el-table-column prop="unit" label="物料单位" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="物料单价" width="110px" header-align="center">
          	<template slot-scope="scope">
              <div v-if="scope.row.canSelect">
                <el-input-number is-decimal-zero class="table-input" v-model="scope.row.unitPrice" :min="0" :precision="globalConfig.pricePrecision" size="mini" :controls="false" @click.native.stop>
                </el-input-number>
              </div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="采购税率" width="90px" header-align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.canSelect&&scope.row.provider.isTax">
                <el-input-number v-model="scope.row.tax" :min="0" :max="100" :precision="0" size="mini" :controls="false" style="width:60px;" @click.native.stop>
                </el-input-number>
                <span>%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="单付投料数" width="130px" header-align="center">
            <template slot-scope="scope" v-if="scope.row.canSelect">
              <div v-if="scope.row.unit==='付'" style="text-align:center">{{scope.row.singleFeedCount}}</div>
              <el-input-number is-decimal-zero v-else v-model="scope.row.singleFeedCount" class="table-input" :min="0" :precision="4" size="mini" :controls="false" @click.native.stop
                @change="singleFeedCountChange(scope.row)">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="车间" width="200px" header-align="center">
            <template slot-scope="scope" v-if="scope.row.canSelect">
              <workshop-select v-model="scope.row.workshop" class="table-input" size="mini" :order="scope.row" @change="workshopChange(scope.row)"></workshop-select>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="车间数量" width="130px" align="center">
            <template slot-scope="scope" v-if="scope.row.canSelect">
              <span>{{getWorkshopCount(scope.row)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200px" align="center">
            <template slot-scope="scope" v-if="scope.row.canSelect">
              <el-input v-model="scope.row.feedOrderRemark" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" width="35px" type="selection" :selectable="canSelect" fixed="right" align="center"></el-table-column>
        </el-table>
      </div>

      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" :page-sizes="[10, 15, 20, 40, 50]" @change="pageChange"></table-pagination>

      <el-dialog v-dialogdrag fullscreen class="dialog-fullscreen" title="选择物料" :visible.sync="openSelectDialog" custom-class="materialDialog" @closed="selectDialogClosed" top="10vh">
        <div style="height:100%;overflow:auto;">
          <select-material-form ref="selectMaterialForm" v-if="openSelectDialog" :detail-list="detailList" :order="selectOrder" @update-material="updateMaterial"
            @save-success="saveSelectSuccess"></select-material-form>
        </div>
      </el-dialog>

      <el-dialog title="保存物料" :visible.sync="openUpdateDialog" width="70%" custom-class="materialDialog" @closed="updateDialogClosed"
        top="10vh">
        <div style="height:70vh;overflow:auto;">
          <feed-material-form v-if="openUpdateDialog" mode="nonFeed" :feed="selectOrder" :dropdown-option="formDropdownOption" @update-success="saveUpdateSuccess"
            @close-dialog="openUpdateDialog=false"></feed-material-form>
        </div>
      </el-dialog>

      <el-dialog title="设置生产投料数" :visible.sync="openCountDialog" @closed="countDialogClosed">
        <div style="height:260px;overflow:auto;">
          <pro-count-form v-if="openCountDialog" :pro-order="selectOrder" :pro-stock="proStock" @update="updateSuccess"></pro-count-form>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [
      tablePaginationMixin(),
      datePickerOptionsMixin('orderDateStart', 'orderDateEnd'),
    ],
    computed: {
      materialTypeCountList: function () {
        var orderList = this.selectOrderList;
        if (orderList.length === 0) {
          return [];
        }

        var orderGroup = _.groupBy(orderList, function (obj) {
          var materialType = obj.materialType;
          if (SysUtil.isEmpty(materialType)) {
            return '无';
          }
          return materialType;
        });
        var countList = [];
        for (const materialType in orderGroup) {
          var list = orderGroup[materialType];
          var count = _.sumBy(list, function (obj) {
            var feedTotal = obj.feedTotal;
            if (SysUtil.isEmpty(feedTotal)) {
              return 0;
            }
            return feedTotal;
          });
          countList.push({
            materialType: materialType,
            count: count
          });
        }
        return countList;
      }
    },
    data: function () {
      var search = {
        materialFactory: '',
        materialName: '',
        materialType: '',
        model: '',
        color: '',
        providerName: '',
        factoryNo: '',
        orderId: '',
        companyOrderId: '',
        customerNo: '',
        customer: '',
        providerNo: '',
        materialDept: '',
        orderType: '',
        orderDateStart: null,
        orderDateEnd: null
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        orderList: [],
        selectOrderList: [],
        openSelectDialog: false,
        openUpdateDialog: false,
        openCountDialog: false,
        selectOrder: null,
        formDropdownOption: null,
        proStock: null,
        detailList: [],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10
        },
        unitList: [],
        orderTypeList: [],
        dealerList: null,
        dealerObj: null,
        allDealerObj: null,
        user: null,
        canUpdateFeedCount: false,
        searchForm: ['materialName', 'materialType', 'model', 'color', 'providerName', 'materialDept', 'orderId', 'companyOrderId', 'factoryNo',
          'customerNo', 'customer'
        ],
        i18n: i18n
      };
    },
    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setUnitList(),
        this.setDealerList(),
        this.setOrderTypeList(),
        this.setUser()
      ]).then(function () {
        return self.setOrderList(true).then(function () {
          self.loading = false;
        });
      }).catch(function () {
        self.loading = false;
      });
    },
    methods: {
      setUnitList: function () {
        var self = this;
        return DropdownUtil.getUnitList().then(function (unitList) {
          self.unitList = unitList;
          return unitList;
        });
      },
      setDealerList: function () {
        var self = this;
        return DropdownUtil.getDealerList().then(function (res) {
          self.dealerList = res.dealerList;
          self.dealerObj = res.dealerObj;
          self.allDealerObj = res.allDealerObj;
          return res;
        });
      },
      setOrderTypeList: function () {
        var self = this;
        ajaxRequest('order/getOrderType').then(function (orderTypeList) {
          self.orderTypeList = orderTypeList;
          return orderTypeList;
        });
      },
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          self.canUpdateFeedCount = user.companyInfo.isUpdateFeedOrderFeedTotal !== 0;
          return user;
        });
      },
      setOrderList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var pagination = this.pagination;
        var pageSize = pagination.pageSize;
        var start = (pagination.currentPage - 1) * pageSize;

        var search = this.search;
        var postData = {
          start: start,
          length: pageSize,
          materialFactory: search.materialFactory
        };

        var fields = ['materialName', 'materialType', 'model', 'color', 'providerName', 'factoryNo', 'orderId', 'companyOrderId',
          'customerNo', 'customer', 'providerNo', 'orderType'
        ];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        var orderDateStart = search.orderDateStart;
        if (orderDateStart !== null) {
          postData.orderDateStart = moment(orderDateStart).format('YYYY-MM-DD');
        }

        var orderDateEnd = search.orderDateEnd;
        if (orderDateEnd !== null) {
          postData.orderDateEnd = moment(orderDateEnd).format('YYYY-MM-DD');
        }

        var dealerObj = this.dealerObj;
        var self = this;
        return ajaxRequest("productionUnitFeed/getOrderInfoDetailByNotFeed", postData, false).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var orderList = res.returnData;
          orderList = _.map(orderList, function (order) {
            order = new NonFeedOrderModel(order, dealerObj);
            return order;
          });

          self.orderList = orderList;
          pagination.totalCount = res.iTotalRecords;
          return orderList;
        });
      },
      resetOrderList(isSearch) {
        this.loading = true;
        var self = this;
        var currentPage = this.pagination.currentPage;
        this.setOrderList(isSearch).then(function (orderList) {
          self.loading = false;
          if (!isSearch && orderList.length === 0) {
            if (currentPage > 1) {
              self.resetOrderList();
            }
          }
        }).catch(function () {
          self.loading = false;
        });
      },
      resetSearch() {
        this.search = _.cloneDeep(this.oldSearch);
      },
      resetDropdown: function () {
        this.$refs['searchRef'].clearList();
      },
      searchData: function () {
        this.pagination.currentPage = 1;
        this.resetOrderList(true);
      },
      pageChange: function () {
        this.resetOrderList();
      },
      rowClick: function (order, column) {
        if (order.materialCode === '') {
          this.getMaterialDetail(order);
        } else {
          if (!column) {
            return;
          }
          var columnKey = column.columnKey;
          if (columnKey === undefined) {
            return;
          }
          this.toUpdateProCount(order);
        }
      },
      getMaterialDetail: function (order) {
        var postData = order.getDetailObject();
        this.loading = true;
        var self = this;
        return ModuleUtil.getFeedMaterialDetail(postData, order, 'selectFeed').then(function (detailList) {
          self.selectOrder = order;
          if (detailList !== null) {
            detailList = _.filter(detailList, function (detail) {
              return detail.materialCode !== '';
            });
          }
          if (detailList === null || detailList.length === 0) {
            self.toOpenUpdateDialog();
          } else {
            self.detailList = detailList;
            self.openSelectDialog = true;
          }
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },
      updateMaterial: function () {
        this.openSelectDialog = false;
        this.toOpenUpdateDialog();
      },
      toOpenUpdateDialog: function () {
        this.formDropdownOption = {
          unitList: this.unitList
        };
        this.openUpdateDialog = true;
      },
      saveSelectSuccess: function () {
        this.openSelectDialog = false;
        this.resetOrderList();
      },
      selectDialogClosed: function () {
        this.detailList = [];
        if (!this.openUpdateDialog) {
          this.selectOrder = null;
        }
      },
      saveUpdateSuccess: function () {
        this.openUpdateDialog = false;
        this.resetOrderList();
      },
      updateDialogClosed: function () {
        this.selectOrder = null;
        this.formDropdownOption = null;
      },
      toUpdateProCount: function (order) {
        if (order.unit === '付') {
          return;
        }

        var postData = {
          materialCode: order.materialCode,
          orderId: order.orderNo,
          materialType: order.materialType,
          materialFactory: order.materialFactory,
          materialName: order.materialName,
          model: order.materialModel,
          color: order.color,
          providerName: order.providerName,
          inOutUnit: order.unit
        };
        this.loading = true;
        var self = this;
        ajaxRequest('productionUnitFeed/getProductionUnitCount', postData).then(function (res) {
          self.loading = false;
          var count = res.productionUnitFeedCount;
          var flag = false;
          if (count === 0) {
            flag = true;
          } else {
            var proTotal = self.getProTotalCount(order);
            count = _.round(count - proTotal, 2);
            if (count <= 0) {
              flag = true;
            } else {
              res.productionUnitFeedCount = count;
            }
          }
          if (flag) {
            return;
          }

          var proStock = new ProStockInfoModel(order, res);
          self.proStock = proStock;
          self.selectOrder = order;
          self.openCountDialog = true;
        }).catch(function () {
          self.loading = false;
        });
      },
      getProTotalCount: function (order) {
        var orderList = this.orderList;
        var materialCode = order.materialCode;
        orderList = _.filter(orderList, function (obj) {
          return obj.materialCode === materialCode && obj.id !== order.id;
        });

        var count = _.sumBy(orderList, 'productionUnitFeedCount');
        count = _.round(count, 2);
        return count;
      },
      updateSuccess: function () {
        this.openCountDialog = false;
      },
      countDialogClosed: function () {
        this.proStock = null;
        self.selectOrder = null;
      },
      getRowClassName: function (option) {
        var order = option.row;
        if (order.materialCode === '') {
          return 'noMaterialCode';
        }
        return '';
      },
      canSelect: function (order) {
        return order.canSelect;
      },
      selectNonFeedorder: function (selectOrderList) {
        this.selectOrderList = selectOrderList;
      },
      saveAsFeedAndPurchase: function () {
        this.saveOrder(true);
      },
      saveOrder(createAll) {
        var selectOrderList = this.selectOrderList;
        if (selectOrderList.length === 0) {
          this.$alert('请选择需要保存的数据', '信息');
          return;
        } else if (selectOrderList.length > 10) {
          this.$alert('所选择需要保存的数据不能超出10条', '信息');
          return;
        }

        var orders = [];
        var hasDecimal = false;
        for (var i = 0; i < selectOrderList.length; i++) {
          var order = selectOrderList[i];
          var code = order.checkValid();
          if (code !== '') {
            var msg = i18n.getMsg(`feddingBill.error.${code}`);
            this.$alert(msg, '信息');
            return;
          }

          if (!hasDecimal) {
            var actualFeedCount = order.actualFeedCount;
            var num = Math.ceil(actualFeedCount);
            if (actualFeedCount !== num) {
              hasDecimal = true;
            }
          }

          var orderPostData = order.getObject();
          orders.push(orderPostData);
        }

        if (hasDecimal) {
          var self = this;
          this.$confirm('所选择的数据里实际投料数含有小数，是继续保存，还是去修改为整数', '提示', {
            confirmButtonText: '继续保存',
            cancelButtonText: '去修改为小数'
          }).then(function () {
            self.toSaveOrder(orders, createAll);
          });
          return;
        }
        this.toSaveOrder(orders, createAll);
      },
      toSaveOrder: function (orders, createAll) {
        var orderIds = _.map(orders, function (order) {
          return {
            orderId: order.feedOrderId,
            haveYltsTotal: order.haveYltsTotal
          };
        });
        orderIds = _.uniqBy(orderIds, 'orderId');

        var postData = {
          feedOrderDetailArray: JSON.stringify(orders),
          feedOrderMainArray: JSON.stringify(orderIds),
          isAllCreate: createAll ? 'yes' : 'no'
        };

        this.loading = true;
        var self = this;
        ajaxRequest('productionUnitFeed/saveBatchFeedOrder', postData).then(function () {
          self.loading = false;
          self.$alert('保存成功', '信息', {
            callback: function () {
              self.resetOrderList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },
      singleFeedCountChange: function (order) {
        order.calCountData('actualFeedCount');
        this.toChangeFeedTotal(order);
      },
      actualFeedCountChange: function (order) {
        order.calCountData('singleFeedCount');
        this.toChangeFeedTotal(order);
      },
      toChangeFeedTotal: function (order) {
        var workshop = order.workshop;
        if ((this.canUpdateFeedCount || order.unit !== '付') && workshop !== null) {
          var actualFeedCount = order.actualFeedCount;
          if (actualFeedCount <= workshop.stockCount) {
            order.feedTotal = order.actualFeedCount;
          }
        }
      },
      getWorkshopCount: function (order) {
        var actualFeedCount = order.actualFeedCount;
        var workshop = order.workshop;
        if (workshop === null) {
          return '';
        }
        var workshopCount = _.min([actualFeedCount, workshop.stockCount]);
        return workshopCount;
      },
      workshopChange: function (order) {
        var workshop = order.workshop;
        if (workshop === null) {
          return;
        }

        if (this.canUpdateFeedCount || order.unit !== '付') {
          order.feedTotal = order.actualFeedCount;
        }
      }
    },
    components: {
      CheckboxTableColumn: CheckboxTableColumn,
      SelectMaterialForm: SelectMaterialForm,
      FeedMaterialForm: FeedMaterialForm,
      CommonSearchForm: CommonSearchForm,
      SearchBtnView: SearchBtnView,
      ProCountForm: ProCountForm,
      WorkshopSelect: WorkshopSelect,
      TableDealerSelect: TableDealerSelect,
      SysAutocomplete: SysAutocomplete
    },
    template: template
  };
}();
